<?php

namespace app\api\model;

use think\facade\Session;
use think\Model;
use think\model\concern\SoftDelete;

class Comment extends Model
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;
    static $uid = 0;
    static $art_id = 0;
    public function userInfo()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }
   
    public function articleInfo()
    {
        return $this->belongsTo(Article::class, 'art_id', 'id');
    }
    // 文章评论
    public static function list()
    {
        // 1 为 全部评论 2 ：楼主评论
        $type = input('type', 1);
        $limit = input('limit', 10);
        if (!is_numeric($limit)) $limit = 10;
        // 包含软删除的记录
        $list = self::with(['userInfo' => function ($query) {
            $query->field('id, nickname, avator');
        }]);
        $art_id = self::$art_id;
        $uid = self::$uid;
        if (!empty($art_id)) {
            // 查询指定文章的评论
            $list->where(['art_id' => $art_id]);
            if ($type == 2) {
                $art = Article::where(['id' => $art_id])->find();
                $list->where(['user_id' => @$art['user_id'] ?? 0]);
            }
            $list->withTrashed();
        } else {
            $exist = User::findOrEmpty($uid)->isEmpty();
            if ($exist) return error('用户不存在');
            $list->where(['user_id' => $uid])
                ->with(['articleInfo' => function ($query) {
                    $query->field('id, title');
                }]);
        }

        $list = $list->order('id asc')->paginate($limit)->each(function ($item) {
            $item->format_time = formatMessageTime($item->create_time);

            // 检查当前评论是否被软删除
            if ($item->trashed()) {
                $item->comment = '该评论已被删除';
            }

            if ($item['pid'] != 0) {
                // 查询父评论，包含软删除的记录
                $parent = self::with(['userInfo' => function ($query) {
                    $query->field('id, avator, nickname');
                }])->withTrashed()->where(['id' => $item['pid']])->find();

                if ($parent) {
                    // 如果父评论存在，返回父评论内容和父评论 ID
                    $item->parent_id = $parent['id'];
                    $item->parent_comment = $parent->trashed() ? '该评论已被删除' : $parent['comment'];
                    $item->parent_user = $parent['userInfo'];
                    $item->parent_floor = $parent['floor'];
                    $item->parent_format = formatMessageTime($parent['create_time']);
                } else {
                    // 如果父评论被删除，返回父评论 ID，并设置提示
                    $item->parent_id = $item['pid']; // 返回父评论 ID
                    $item->parent_comment = '该评论已被删除';
                    $item->parent_user = null; // 父评论用户信息置空
                    $item->parent_format = formatMessageTime($parent['create_time']);
                }
            }
            return $item;
        });
        return success($list);
    }
}
